<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

class usuarioModel extends CI_Model {

    function __construct() {
        // Call the Model constructor
        parent::__construct();
    }
    
     public function getByProfesor($id){
        $sql = "SELECT u.*"  
                 . " FROM usuarios u "
                . "WHERE profesor = $id ";
        
        $query = $this->db->query($sql);
        
        return $query->result();
    }
    
    public function noExiste($id,$usuario){
        $sql = "SELECT u.*"  
                 . " FROM usuarios u "
                . "WHERE profesor <> $id "               
                . "AND u.usuario = '$usuario'";
        
        $query = $this->db->query($sql);
        
        return count($query->result()) == 0;
    }
    
    public function tieneUsuario($id){
        $sql = "SELECT u.*"  
                 . " FROM usuarios u "
                . "WHERE profesor = $id ";
        
        $query = $this->db->query($sql);
        
        return count($query->result()) == 1;
    }
    
    public function crear($id,$usuario, $pass){
         $sql = "INSERT INTO usuarios (usuario,contrasena,profesor) 
        VALUES ('$usuario', '$pass', $id)";
       
        $this->db->query($sql);
        if($this->db->affected_rows() > 0){
            
            return $this->db->insert_id();
        }else{            
            return $this->db->affected_rows();
        }
    }
    
    public function modificar($id,$usuario, $new_pass){
        $sql = "UPDATE usuarios SET usuario = '$usuario',contrasena = '$new_pass'
        where profesor = $id";
        $this->db->query($sql);
        
        if($this->db->affected_rows() > 0){
            return 1;
        }else{
            return 0;
        }
    }
    
    public function getByUsuario($usuario){
        $sql = "SELECT  u.usuario, u.contrasena, u.perfil, p.* "  
                 . "FROM  usuarios u, profesores p "
                . " WHERE u.usuario = '$usuario'"
                . " AND p.id = u.profesor";
        
        $q = $this->db->query($sql);
        
        $data = $q->result_array();
        if(count($data) > 0){
            return $data[0];
        }else{
            return null;
        }
    }
}